package cn.com.joyplus.wechat.configuration;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * Created by 王灏川(wangrs@qq.com) on 2017/8/11 0011.
 */
@Configuration
@EnableCaching
public class CacheConfig {
    public final static String CACHE_FOR_DEFAULT = "Default";
    public final static String CACHE_FOR_WXMSG = "WxMsgById";
    public final static String CACHE_FOR_ACCESSTOKEN = "AccessonToken";

    /**
     * 创建基于Caffeine的Cache Manager
     *
     * @return
     */
    @Bean
    @Primary
    public CacheManager caffeineCacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();

        ArrayList<CaffeineCache> caches = new ArrayList<>();
        caches.add(new CaffeineCache(CACHE_FOR_DEFAULT,
                Caffeine.newBuilder().recordStats()
                        .expireAfterWrite(300, TimeUnit.SECONDS)
                        .maximumSize(1000)
                        .build())
        );
        caches.add(new CaffeineCache(CACHE_FOR_WXMSG,
                Caffeine.newBuilder().recordStats()
                        .expireAfterWrite(10, TimeUnit.SECONDS)
                        .maximumSize(1000)
                        .build())
        );

        caches.add(new CaffeineCache(CACHE_FOR_ACCESSTOKEN,
                Caffeine.newBuilder().recordStats()
                        .expireAfterWrite(7000, TimeUnit.SECONDS)
                        .maximumSize(20)
                        .build())
        );
        cacheManager.setCaches(caches);

        return cacheManager;
    }

}
